/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》  http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 */
<template>
  <div>
    <s-header :name="'购物车'" :noback="true"></s-header>
    <div class="cart-body">
      <van-checkbox-group @change="groupChange" v-model="result" ref="checkboxGroup">
        <van-cell :right-width="50" v-for="(item, index) in list" :key="index">
          <div class="goods-item">
            <van-checkbox :name="item.id" />
            <img class="goods-img" :src="item.squarePic" alt="" />
            <div class="goods-desc">
              <div class="goods-title">
                <span>{{ item.name }}</span>
              </div>
              <div class="goods-btn">
                <div class="price">¥{{ item.price / 100 }}</div>
                <van-stepper integer :min="0" :model-value="item.quantity" :name="item.id" async-change @change="onChange" />
              </div>
            </div>
          </div>
        </van-cell>
      </van-checkbox-group>
    </div>
    <van-submit-bar v-if="!isLoggedIn" class="login-row" button-text="立即登录" @submit="gotoLoginPage()">
      <div class="login-tips">登录后查看已加购商品</div>
    </van-submit-bar>
    <van-submit-bar v-else-if="list.length > 0" class="create-order-row" :price="totalAmount" button-text="结算" @submit="gotoCreateOrder">
      <van-checkbox @click="allCheck" v-model:checked="checkAll">全选</van-checkbox>
    </van-submit-bar>

    <nav-bar></nav-bar>
  </div>
</template>

<script>
import { reactive, onMounted, computed, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import navBar from '@/components/BottomNav'
import sHeader from '@/components/MyHeader'
import { getStorage } from '@/common/js/utils'
import { queryCart, modifyCart } from '@/service/axios-services'

export default {
  components: {
    navBar,
    sHeader
  },
  setup() {
    const router = useRouter()
    const state = reactive({
      checked: false,
      list: [],
      all: false,
      isLoggedIn: false,
      result: [],
      checkAll: true
    })

    onMounted(() => {
      init()
    })

    const init = async () => {
      const token = getStorage('token')
      if (token) {
        state.isLoggedIn = true
        Toast.loading({ message: '加载中...', forbidClick: true })
        const { data } = await queryCart({ pageNumber: 1 })
        state.list = data
        state.result = data.map((item) => item.id)
        Toast.clear()
      } else {
        state.isLoggedIn = false
      }
    }

    const totalAmount = computed(() => {
      let sum = 0
      let cartItmes = state.list.filter((item) => state.result.includes(item.id))
      cartItmes.forEach((item) => {
        sum += item.quantity * item.price
      })
      return sum
    })

    const gotoLoginPage = () => {
      router.push({ path: '/login' })
    }

    const goBack = () => {
      router.go(-1)
    }

    const onChange = async (value, detail) => {
      if (state.list.filter((item) => item.id == detail.name)[0].quantity == value)
        return
      const params = {quantity: value}
      await modifyCart(detail.name, params)
      state.list.forEach((item) => {
        if (item.id == detail.name) {
          item.quantity = value
        }
      })
      Toast.clear()
      if (value < 1) {
        init()
      }
    }

    const gotoCreateOrder = async () => {
      if (state.result.length == 0) {
        Toast.fail('请选择商品进行结算')
        return
      }
      const params = state.result.join(',')
      router.push({ path: '/create-order', query: { cartItemIds: params } })
    }

    const groupChange = (result) => {
      if (result.length == state.list.length) {
        state.checkAll = true
      } else {
        state.checkAll = false
      }
      state.result = result
    }

    const allCheck = () => {
      if (!state.checkAll) {
        state.result = state.list.map((item) => item.id)
      } else {
        state.result = []
      }
    }

    return {
      ...toRefs(state),
      totalAmount,
      goBack,
      onChange,
      gotoLoginPage,
      gotoCreateOrder,
      groupChange,
      allCheck
    }
  }
}
</script>

<style>
.cart-body {
  margin: 16px 0 100px 0;
  padding-left: 10px;
  padding-bottom: 70px;
}
.goods-item {
  display: flex;
}
.goods-img {
  width: 100px;
  height: 100px;
} 
.goods-desc {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
  padding: 20px;
}
.goods-title {
  display: flex;
  justify-content: space-between;
}
.goods-btn {
  display: flex;
  justify-content: space-between;
}
.price {
  font-size: 16px;
  color: red;
  line-height: 28px;
} 
.create-order-row {
  margin-bottom: 50px;
}
.van-checkbox {
  margin-left: 10px;
}
.van-submit-bar__text {
  margin-right: 10px;
}
.van-submit-bar__button {
  background: #EF3965;
}
.login-row {
  margin-bottom: 50px;
}
.login-tips {
  padding-right: 10px;
}
.van-checkbox__icon--checked .van-icon {
  background-color: #EF3965;
  border-color: #EF3965;
}
</style>
